//
//  PictureBrowserViewController.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/5.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PictureBrowserViewController: UIViewController {
    
    //图像数组
    private var imageURLs: [NSURL]
    
    //用户选中的照片索引
    private var currentIndex: Int
    
    init(urls: [NSURL], index: Int){
    
        imageURLs = urls
        currentIndex = index

        //swfit中有个规定，先初始化本类的属性，再调用父类的构造函数
        super.init(nibName: nil, bundle: nil)
    }
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        
        view.addSubview(collectionView)
        view.addSubview(saveBtn)
        view.addSubview(closeBtn)
        
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        collectionView.ff_Fill(view)
        closeBtn.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        saveBtn.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        
        //准备collectionview视图
        prepareForCollectionView()

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //print("PictureBrowserViewController  ===> \(imageURLs)")
    }
    
    //=====   探索 collectionview 的 layout布局  要放在的地方
    /*
      viewWillAppear()          (0.0, 0.0, 375.0, 667.0)  (0.0, 0.0, 0.0, 0.0)
      viewWillLayoutSubviews()  (0.0, 0.0, 375.0, 667.0)  (0.0, 0.0, 0.0, 0.0)
      viewDidLayoutSubviews()   (0.0, 0.0, 375.0, 667.0)  (0.0, 0.0, 375.0, 667.0)
    */
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
       // print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
       // print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
    }
    
    // 在 viewDidLayoutSubviews 中 collectionView才会有  frame
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
       // print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
        
        prepareForLayout()
        
        // ！！！！跳转到用户选定的页面
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        
    }
    
    
    //设置collectionview的布局  layout
    private func prepareForLayout() {
        
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
    
        //print(__FUNCTION__)
        //拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PictureBrowserCell
        
        //拿到图像
        let image = cell.picImageView.image
        
        // 保存图像,,  次方法的  回调函数的格式是固定的， 必须实现
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //有两个名字的参数： 外边使用左边的名字，，里面使用右面的名字
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:AnyObject) {
    
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    private func prepareForCollectionView() {
        collectionView.dataSource = self
        collectionView.registerClass(PictureBrowserCell.self, forCellWithReuseIdentifier: PictureBrowserCellReuseIdentifier)
    }
    
    //懒加载控件
    // collectionView先设置成0，CGRectZero， 大小由自动布局来定
    lazy private var layout = UICollectionViewFlowLayout()//UICollectionViewLayout()
    
    // 后面括号内部是一个简写的  “闭包”，   所以 layout 要写成  self.layout
    lazy private var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    lazy private var saveBtn: UIButton = UIButton(title:"保存", fontSize:14)
    lazy private var closeBtn: UIButton = UIButton(title:"取消", fontSize:14)
    
    
    //交互式转场需要的变量：图片缩放比例
    private var pictureScale: CGFloat = 0
}

private let PictureBrowserCellReuseIdentifier = "PictureBrowserCellReuseIdentifier"

extension PictureBrowserViewController: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
       // print("哈哈哈哈哈哈   ＝＝＝》 \(imageURLs.count)")
        return imageURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PictureBrowserCell
        cell.backgroundColor = UIColor.randomColor()
        
        cell.cellDelegate = self
        
        cell.imageURL = imageURLs[indexPath.item]
        
        return cell
    }
}

extension PictureBrowserViewController: PictureBrowserDelegate {
    
    func PictureBrowserDidTap(cell: PictureBrowserCell) {
       
        //print("手势手势   ＝＝＝＝  手势手势")
        close()
    }
    
    func PictureBrowserDidZooming(scale: CGFloat) {
        print(" PictureBrowserDidZooming  ===> \(scale)")
        
        //实现交互式转场
        //记录缩放比例
        pictureScale = scale
        
        //如果缩放比例 < 1,就开始交互式转场
        if pictureScale < 1.0 {
            //参数写 self，必须实现协议所应该的方法
            startInteractiveTransition(self)
        }
    }
    
    func PictureBrowserEndZoom() {
        if pictureScale < 0.8 {
        
            //dismissViewControllerAnimated(true, completion: nil)
            //直接关闭图片浏览器视图，，告诉转场动画结束
            completeTransition(true)
        }
    }
}

//实现交互式转场
extension PictureBrowserViewController: UIViewControllerInteractiveTransitioning {
    
    //transitionContext  提供转场所需的 所有信息
    //参数“UIViewControllerContextTransitioning”  是一个协议
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning){
        
        //在这里面缩放视图
        view.transform = CGAffineTransformMakeScale(pictureScale, pictureScale)
        //设置透明度
        view.alpha = pictureScale

    }
}

//参数应该遵守的协议, 里面的方法没有optional ,所以必须全部实现，但是只有一个有用
extension PictureBrowserViewController: UIViewControllerContextTransitioning {

    //转场动画中，这个函数很重要，告诉转场动画已经结束，这也是   “唯一需要实现的函数”
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
   
    func containerView() -> UIView? { return self.view.superview }
    
    func isAnimated() -> Bool { return true }
    
    func isInteractive() -> Bool { return true }
    
    func transitionWasCancelled() -> Bool { return true }
    
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    
    func updateInteractiveTransition(percentComplete: CGFloat) { }
    func finishInteractiveTransition() { }
    func cancelInteractiveTransition() { }
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    
    func viewForKey(key: String) -> UIView? {return self.view}
   
    func targetTransform() -> CGAffineTransform {return CGAffineTransformIdentity}
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}
